//
//  ModelListViewController.m
//  CheXunWang
//
//  Created by zhu lin on 12/18/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "ModelListViewController.h"
#import "StorageService.h"
#import "HttpServices.h"
#import "CustomBarButtonItem.h"
#import "ModelInfoCell.h"
#import "ImageListViewController.h"
#import "SBJSON.h"
#import "ModelDetailViewController.h"

/*
 {
 "english":"audi-q5",
 -"seriesId":2102,
 -"guidePrice":"37.98-56.77万元",
 -"imagePath":"http://photo.chexun.com/images/auto/2011-11/aodi/aodiq5/20tsidgx/12090/20111130153345771458490.jpg",
 "brandId":2,
 "companyId":81,
 "importType":"1",
 "recommendSort":"5",
 -"features":"奥迪最便宜的SUV，但是没和途观拉开档次，价格不占优势",
 "brandName":"奥迪",
 -"companyName":"一汽奥迪",
 -"guidePriceFor4S":"37.98-56.77万元",
 -"seriesName":"奥迪Q5"}
 */

#define kDefaultSectionNum		1
#define kDefaultCellNum			1
#define kCustomSectionHeight	20.0
#define kCustomCellHeight		80.0
#define kCustomBlankCellHeight	269.0

#define kSeriesID				@"seriesId"
#define kSeriesName				@"seriesName"
#define kSeriesImagePath		@"imagePath"
#define kSeriesGuidePrice		@"guidePrice"
#define kSeriesGuidePriceFor4S	@"guidePriceFor4S"

#define kSectionKey				@"year"
#define kModelID				@"modelId"
#define kModelName				@"modelName"
#define kModelGuidePrice		@"guidePrice"
#define kModelGuidePriceFor4S	@"guidePriceFor4S"
#define kModelImagePath			@"imagePath"

@interface ModelListViewController()
@property (nonatomic, retain) NSMutableArray			*groupedModelArray;
@property (nonatomic, retain) ASIHTTPRequest			*seriesImageRequest;
@property (nonatomic, retain) ASIHTTPRequest			*modellistRequest;
@property (nonatomic, retain) ASIHTTPRequest			*photoCountRequest;

- (void)popViewController:(id)sender;
- (void)loadSeriesInfo;
- (UIImage *)loadSeriesImage;
- (void)loadModellist;
- (void)loadPhotoCount;
@end

@implementation ModelListViewController
@synthesize seriesImageView;
@synthesize imageCountLabel;
@synthesize priceLabel;
@synthesize priceFor4SLabel;
@synthesize modellistTableView;

@synthesize seriesInfoDic;
@synthesize groupedModelArray;
@synthesize seriesImageRequest;
@synthesize modellistRequest;
@synthesize photoCountRequest;

@synthesize scopeValue;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.hidesBackButton = YES;
	CustomBarButtonItem *backButton = [[CustomBarButtonItem alloc] initWithTitle:@"车 系" style:LeftBarButtonItemBackStyle target:self action:@selector(popViewController:)];
	self.navigationItem.leftBarButtonItem = backButton;
	[backButton release];
	self.modellistTableView.tableFooterView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 0)] autorelease];

	self.groupedModelArray = [NSMutableArray array];
	[self loadSeriesInfo];
	[self loadModellist];
	[self loadPhotoCount];
}

- (void)popViewController:(id)sender
{	
	[self.navigationController popViewControllerAnimated:YES];
}


- (void)loadSeriesInfo
{
	if (self.seriesInfoDic != nil) {
		self.priceLabel.text = [self.seriesInfoDic valueForKey:kSeriesGuidePrice];
		self.priceFor4SLabel.text = [self.seriesInfoDic valueForKey:kSeriesGuidePriceFor4S];
		self.seriesImageView.image = [self loadSeriesImage];
	}
}

- (void)loadModellist
{
	if (self.seriesInfoDic != nil) {
		self.modellistRequest = [HttpServices getModellistBySeriesID:[[self.seriesInfoDic valueForKey:kSeriesID] stringValue] 
														  priceScope:self.scopeValue
															delegate:self];
	}
}

- (void)loadPhotoCount
{
	if (self.seriesInfoDic != nil) {
		self.photoCountRequest = [HttpServices getCarPhotoCountBySeriesId:[[self.seriesInfoDic valueForKey:kSeriesID] stringValue] 
																  modelId:nil 
															  andDelegate:self];
	}
}

- (UIImage *)loadSeriesImage
{
	if (self.seriesInfoDic != nil)
	{
		NSString *imageURL = (NSString *)[self.seriesInfoDic valueForKey:kSeriesImagePath];
		NSString *imageName = (NSString *)[[imageURL componentsSeparatedByString:@"/"] lastObject];
		NSString *imagePath = [StorageService getPathByStorageType:ZLStorageTypeSeriesImage withFileName:imageName];
		
		if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
			return [UIImage imageWithContentsOfFile:imagePath];
		} else {
			if (self.seriesImageRequest == nil) {
				self.seriesImageRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageURL]];
				[self.seriesImageRequest setDelegate:self];
				[self.seriesImageRequest setDownloadDestinationPath:imagePath];
				[self.seriesImageRequest startAsynchronous];
			}
		}
	}
	
	return [UIImage imageNamed:@"ios_common_list_item_avatar.png"];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[self.seriesImageRequest clearDelegatesAndCancel];
	[self.modellistRequest clearDelegatesAndCancel];
	[self.photoCountRequest clearDelegatesAndCancel];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
	[self.groupedModelArray removeAllObjects];
	[self.seriesImageRequest clearDelegatesAndCancel];
	self.seriesImageRequest = nil;
	[self.modellistRequest clearDelegatesAndCancel];
	self.modellistRequest = nil;
	[self.photoCountRequest clearDelegatesAndCancel];
	self.photoCountRequest = nil;
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	self.seriesImageView = nil;
	self.imageCountLabel = nil;
	self.priceLabel = nil;
	self.priceFor4SLabel = nil;
	self.modellistTableView = nil;
	
	self.seriesImageRequest = nil;
	self.modellistRequest = nil;
	self.photoCountRequest = nil;
}

- (void)dealloc {
	[photoCountRequest release];
	[seriesImageRequest release];
	[modellistRequest release];
	[seriesImageView release];
	[imageCountLabel release];
	[priceLabel release];
	[priceFor4SLabel release];
	[seriesInfoDic release];
	[groupedModelArray release];
    [super dealloc];
}

#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	int count = [self.groupedModelArray count];
	
    if (count == 0) {
		return kDefaultSectionNum;
	}
	
	return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if ([self.groupedModelArray count] == 0) {
		return kDefaultCellNum;
	}
	
    NSArray *subArray = [self.groupedModelArray objectAtIndex:section];
	if (subArray && [subArray count] > 0) {
		return [subArray count];
	}
	
	return kDefaultCellNum;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([self.groupedModelArray count] == 0) {
		return kCustomBlankCellHeight;
	}
	
	return kCustomCellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	if ([self.groupedModelArray count] == 0) {
		return nil;
	}
	
	UIView *customSectionView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, kCustomSectionHeight)];
	UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ios_common_list_title_bg.png"]];
	backImageView.frame = CGRectMake(0.0, 0.0, 320.0, kCustomSectionHeight);
	[customSectionView addSubview:backImageView];
	[backImageView release];
	UILabel *companyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 300.0f, kCustomSectionHeight)];
	companyLabel.backgroundColor = [UIColor clearColor];
	companyLabel.textColor = [UIColor colorWithRed: 0.2 green: 0.2 blue: 0.2 alpha: 1.0];
	companyLabel.font = [UIFont systemFontOfSize:12.0f];
	NSString *year = (NSString *)[[[self.groupedModelArray objectAtIndex:section] objectAtIndex:0] valueForKey:kSectionKey];
	companyLabel.text = [NSString stringWithFormat:@"%@ 款", year];
	[customSectionView addSubview:companyLabel];
	[companyLabel release];
	return customSectionView;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *blankCellIdentifier = @"blankCell";
	static NSString *modelCellIdentifier = @"modelInfoCell";
    
	if ([self.groupedModelArray count] == 0) {
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:blankCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
										   reuseIdentifier:blankCellIdentifier] autorelease];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		return cell;
	}
	
	ModelInfoCell *cell = (ModelInfoCell *)[tableView dequeueReusableCellWithIdentifier:modelCellIdentifier];
    if (cell == nil)
	{
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ModelInfoCell" owner:self options:nil];
		for(id oneNib in nib)
			if([oneNib isKindOfClass:[ModelInfoCell class]])
				cell = (ModelInfoCell *)oneNib;
	}
    
    // Configure the cell...
	NSDictionary *dic = (NSDictionary *)[[self.groupedModelArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	cell.modelNameLabel.text = (NSString *)[dic objectForKey:kModelName];
	if ([dic objectForKey:kModelGuidePrice] && ![[dic objectForKey:kModelGuidePrice] isEqual:[NSNull null]]) {
		cell.guidePriceLabel.text = [[dic objectForKey:kModelGuidePrice] stringValue];
	}
	cell.guidePriceFor4SLabel.text = (NSString *)[dic objectForKey:kModelGuidePriceFor4S];
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.groupedModelArray count] == 0) {
		return;
	}
	
	NSDictionary *dic = (NSDictionary *)[[self.groupedModelArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
	
    ModelDetailViewController *modelDetailVC = [[ModelDetailViewController alloc] initWithNibName:@"ModelDetailViewController" bundle:nil];
	modelDetailVC.title = (NSString *)[dic objectForKey:kModelName];
	modelDetailVC.modelInfoDic = dic;
	modelDetailVC.hidesBottomBarWhenPushed = YES;
	
	//
	[self.navigationController pushViewController:modelDetailVC animated:YES];
	[modelDetailVC release];
	
	[self.modellistTableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
	if (request == self.seriesImageRequest) {
		self.seriesImageView.image = [self loadSeriesImage];
	} else if (request == self.modellistRequest) {
		//
		NSData *responseData = [request responseData];
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		
		NSArray *ungroupedArray = (NSArray *)[result JSONValue];
		if (!ungroupedArray || [ungroupedArray count] == 0) {
			self.groupedModelArray = [NSMutableArray array];
		} else {
			self.groupedModelArray = [HttpServices groupArray:ungroupedArray byKey:kSectionKey];
		}
		
		[self.modellistTableView reloadData];
	} else {
		NSData *responseData = [request responseData];
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		//[{"imageCount":31}]
		NSString *count = [[(NSDictionary *)[(NSArray *)[result JSONValue] objectAtIndex:0] valueForKey:@"imageCount"] stringValue];
		self.imageCountLabel.text = [NSString stringWithFormat:@"%@张图片",count];
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	if (request = self.seriesImageRequest) {
		self.seriesImageView.image = [self loadSeriesImage];
	} else {
		//
	}
}

#pragma mark -
#pragma mark actions
- (IBAction)showImageList:(id)sender;
{
	ImageListViewController *imageListVC = [[ImageListViewController alloc] init];
	imageListVC.seriesID = [[self.seriesInfoDic valueForKey:kSeriesID] stringValue];
	imageListVC.title = [self.seriesInfoDic valueForKey:kSeriesName];
	imageListVC.hidesBottomBarWhenPushed = YES;
	[self.navigationController pushViewController:imageListVC animated:YES];
	[imageListVC release];
}

- (IBAction)show4SLocation:(id)sender
{
	
}

@end
